import utils from "./util";
import storage from "../storage/storage.js";
import config from "../config/config.js";

export default function request(obj = {}) {
	let token = storage.getItem('token');
	// const headers = {
	// 	'Content-Type': 'application/json; charset=utf-8',
	// 	'token': token
	// };
	return new Promise((resolve, reject) => {
		if (obj.token !== undefined && obj.token == true) {
			obj.data = obj.data || {};
			obj.data.token = token
			// obj.header = headers
		};
		if (obj.loading !== undefined && obj.loading == true) {
			uni.showLoading({
				title: obj.msg || '正在加载',
				mask: true,
			})
		};
		uni[obj.upload ? 'uploadFile' : 'request']({
			...obj,
			url: config.baseUrl + (obj.url || ''),
			method: obj.method || 'POST',
			// header: headers,
			header: obj.header ? Object.assign({}, config.header, obj.header) : config.header,
			[obj.upload ? 'formData' : 'data']: obj.data || {},
			success(res) {
				// if(!uni.getStorageSync('token')) {
				// 	uni.reLaunch({
				// 		url: '/pages/login/src/main'
				// 	})
				// }
				uni.hideLoading();
				if (typeof res.data === 'string') {
					try {
						res.data = JSON.parse(res.data);
					} catch (e) {}
				}
				if (res.data.status == 401 || res.data.status == 403) {
					uni.showModal({
						title: '登录提示',
						content: res.data.info,
						success: ress => {
							if (ress.confirm) {
								uni.redirectTo({
									url: '/pages/login/index'
								})
							}
						}
					})
				}
				// console.log(obj.url, obj.data)
				resolve(res.data)
			},
			fail(err) {
				uni.hideLoading();
				reject(err);
			}

		})
	})
}